<template>
  <div class="p-4 preview-container">
    <h1 class="mb-4 text-xl font-bold text-center">{{ pageData.pageConfig.title }}</h1>
    <div class="p-1 my-2" v-for="item in pageData.components" :key="item.id">
      <component :is="getComponent(item.code)" :component="item"></component>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, shallowRef } from 'vue'

import Button from '../../src/components/Button/index.vue'
import Input from '../../src/components/Input/index.vue'

// 页面数据
const pageData = ref({
  components: [],
  pageConfig: { title: '预览页面' },
})

// 明确提供预览模式文本框可编辑
provide('editorMode', true)

// 获取组件映射
const components = shallowRef({
  button: Button,
  input: Input,
})

// 获取组件
const getComponent = (code) => {
  return components.value[code]
}

onMounted(() => {
  // 从localStorage加载数据
  const storedData = localStorage.getItem('lowcode')
  if (storedData) {
    try {
      const parsed = JSON.parse(storedData)
      pageData.value = parsed.pageConfig
        ? parsed
        : {
            components: parsed,
            pageConfig: { title: '预览页面' },
          }
    } catch (e) {
      console.error('Failed to parse stored data', e)
    }
  }
})
</script>
